<?php

namespace App\Http\Controllers\Single;

use App\Http\Controllers\Controller;
use App\Http\Requests\TermQueryRequest;
use App\Http\Resources\TermCollection;
use App\Http\Resources\TermResource;
use App\Services\TermHierarchyService;
use App\Utils\ApiResponse;
use Illuminate\Http\Request;

class Term extends Controller
{
    /**
     * @group WordPress分类标签
     * @subgroup 分类标签查询
     *
     * 获取WordPress分类或标签列表，支持多种查询条件。
     *
     * @queryParam taxonomy string 分类法类型，默认为category Example: category
     * @queryParam hide_empty boolean 是否隐藏空分类，默认false Example: false
     * @queryParam parent integer 父级ID，获取子分类 Example: 0
     * @queryParam child_of integer 获取指定分类的子分类 Example: 1
     * @queryParam include string 包含的分类ID，多个用逗号分隔 Example: 1,2,3
     * @queryParam exclude string 排除的分类ID，多个用逗号分隔 Example: 4,5,6
     * @queryParam search string 搜索关键词 Example: 技术
     * @queryParam orderby string 排序字段，支持name、count、slug、term_group Example: name
     * @queryParam order string 排序方向，ASC或DESC Example: ASC
     * @queryParam number integer 返回数量限制，0表示不限制 Example: 20
     * @queryParam offset integer 偏移量 Example: 0
     * @queryParam include_children boolean 是否包含子分类，嵌套返回 Example: false
     *
     * @response 200 {
     *   "code": 200,
     *   "message": "获取分类标签成功",
     *   "data": [
     *     {
     *       "id": 1,
     *       "name": "技术",
     *       "slug": "tech",
     *       "description": "技术相关文章",
     *       "count": 10,
     *       "parent": 0,
     *       "taxonomy": "category",
     *       "url": "https://example.com/category/tech/",
     *       "children": [
     *         {
     *           "id": 2,
     *           "name": "前端开发",
     *           "slug": "frontend",
     *           "description": "前端开发相关",
     *           "count": 5,
     *           "parent": 1,
     *           "taxonomy": "category",
     *           "url": "https://example.com/category/frontend/"
     *         }
     *       ]
     *     }
     *   ]
     * }
     *
     * @response 500 {
     *   "code": 500,
     *   "message": "获取分类标签失败: 数据库连接错误",
     *   "data": null
     * }
     *
     * @param TermQueryRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(TermQueryRequest $request)
    {
        try {
            // 构建查询参数
            $args = $request->buildQueryArgs();

            // 执行查询
            $terms = get_terms($args);

            // 检查查询结果
            if (is_wp_error($terms)) {
                return ApiResponse::error('获取分类标签失败: ' . $terms->get_error_message(), 500, 500);
            }

            // 使用Resource格式化数据
            $termResource = new TermCollection($terms);

            return ApiResponse::success($termResource, '获取分类标签成功');
        } catch (\Exception $e) {
            return ApiResponse::error('获取分类标签失败: ' . $e->getMessage(), 500, 500);
        }
    }

    /**
     * @group WordPress分类标签
     * @subgroup 单个分类标签
     *
     * 根据分类或标签ID获取详细信息。
     *
     * @urlParam id integer required 分类或标签ID Example: 1
     * @queryParam taxonomy string 分类法类型，默认为category Example: category
     * @queryParam include_children boolean 是否包含子分类，嵌套返回 Example: false
     *
     * @response 200 {
     *   "code": 200,
     *   "message": "获取分类标签成功",
     *   "data": {
     *     "id": 1,
     *     "name": "技术",
     *     "slug": "tech",
     *     "description": "技术相关文章",
     *     "count": 10,
     *     "parent": 0,
     *     "taxonomy": "category",
     *     "url": "https://example.com/category/tech/",
     *     "children": [
     *       {
     *         "id": 2,
     *         "name": "前端开发",
     *         "slug": "frontend",
     *         "description": "前端技术文章",
     *         "count": 5,
     *         "parent": 1,
     *         "taxonomy": "category",
     *         "url": "https://example.com/category/frontend/",
     *         "children": []
     *       }
     *     ]
     *   }
     * }
     *
     * @response 404 {
     *   "code": 404,
     *   "message": "分类标签不存在",
     *   "data": null
     * }
     *
     * @response 500 {
     *   "code": 500,
     *   "message": "获取分类标签失败: 数据库连接错误",
     *   "data": null
     * }
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function show(Request $request)
    {
        try {
            $id = $request->route('id');
            $taxonomy = $request->get('taxonomy', 'category');

            if (!$id || !is_numeric($id)) {
                return ApiResponse::error('无效的分类标签ID', 400, 400);
            }

            // 获取分类或标签
            $term = get_term($id, $taxonomy);

            if (!$term || is_wp_error($term)) {
                return ApiResponse::error('分类标签不存在', 404, 404);
            }

            // 使用层级服务格式化数据（支持include_children参数）
            $termData = TermHierarchyService::buildSingleTermHierarchy($term, $request);

            return ApiResponse::success($termData, '获取分类标签成功');
        } catch (\Exception $e) {
            return ApiResponse::error('获取分类标签失败: ' . $e->getMessage(), 500, 500);
        }
    }
}
